package com.raising.sc.log.demo.aop;

import com.alibaba.fastjson.JSON;
import com.raising.sc.log.client.annotation.ApiLogger;
import com.raising.sc.log.client.entity.ApiLog;
import com.raising.sc.log.client.service.ApiLogClientService;
import com.raising.sc.log.client.util.HttpUtils;
import com.raising.sc.log.demo.util.UserUtils;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Date;

/**
 * api日志切面
 * @author GaoYuan
 * @date 2018/4/9 下午3:44
 */
@Aspect
@Component
public class ApiLoggerAspect {

    @Autowired
    private ApiLogClientService loggerService;

    @Pointcut("@annotation(com.raising.sc.log.client.annotation.ApiLogger)")
    public void loggerPointCut() {

    }

    @Before("loggerPointCut()")
    public void saveSysLog(JoinPoint joinPoint) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();

        ApiLog sysLog = new ApiLog();
        ApiLogger sysLogger = method.getAnnotation(ApiLogger.class);
        if(sysLogger != null){
            //注解上的描述
            sysLog.setOperation(sysLogger.value());
        }
        //请求的方法名
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = signature.getName();
        sysLog.setMethod(className + "." + methodName + "()");
        //请求的参数
        Object[] args = joinPoint.getArgs();
        String params="";
        for(Object o:args){
            params += JSON.toJSONString(o);
        }
        if(!StringUtils.isEmpty(params)) {
            sysLog.setParams(params);
        }
        //设置IP地址
        sysLog.setIp(HttpUtils.getIpAddress());
        /** 在这里编写获取用户名 */
        String username = UserUtils.getCurrentPrinciple();
        if(!StringUtils.isEmpty(username)) {
            sysLog.setUsername(username);
        }
        sysLog.setCreateDate(new Date());
        //保存系统日志
        loggerService.log(sysLog);
    }


}

